import java.util.Scanner;

public class MySqrt 
{
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        // 测试平方根方法
        System.out.print("Enter a number to compute its square root: ");
        long number = input.nextLong();
        System.out.printf("Square root of %d is: %.4f\n", number, sqrt(number));
        
        // 清除缓冲区
        input.nextLine();
        
        // 测试字符计数方法
        System.out.print("Enter a string: ");
        String str = input.nextLine();
        System.out.print("Enter a character to count: ");
        char ch = input.next().charAt(0);
        
        int count = count(str, ch);
        System.out.printf("The character '%c' appears %d times in \"%s\"\n", ch, count, str);
        
        input.close();
    }
    
    /**
     * 使用巴比伦方法近似计算平方根
     * nextGuess = (lastGuess + n / lastGuess) / 2
     * 
     * @param n 要计算平方根的数
     * @return n的平方根近似值
     */
    public static double sqrt(long n) {
        if (n < 0) {
            throw new IllegalArgumentException("Cannot compute square root of negative number");
        }
        
        double lastGuess = 1.0;  // 初始猜测值
        double nextGuess = (lastGuess + n / lastGuess) / 2;
        
        // 当两次猜测的差小于0.0001时停止
        while (Math.abs(nextGuess - lastGuess) > 0.0001) {
            lastGuess = nextGuess;
            nextGuess = (lastGuess + n / lastGuess) / 2;
        }
        
        return nextGuess;
    }
    
    /**
     * 计算指定字符在字符串中出现的次数
     * 
     * @param str 要搜索的字符串
     * @param a 要计数的字符
     * @return 字符a在str中出现的次数
     */
    public static int count(String str, char a) {
        int count = 0;
        
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == a) {
                count++;
            }
        }
        
        return count;
    }
}
